package cn.legend.travel.destination.main.service.impl;

import cn.legend.travel.common.enumerator.ServiceCode;
import cn.legend.travel.common.exception.ServiceException;
import cn.legend.travel.destination.main.dao.persist.repository.IGuideRepository;
import cn.legend.travel.destination.main.dao.search.GuideElasticsearchRepository;
import cn.legend.travel.destination.main.pojo.vo.GuideVO;
import cn.legend.travel.destination.main.service.IGuideService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GuideService implements IGuideService {
    @Autowired
    private IGuideRepository guideRepository;
    @Autowired
    private GuideElasticsearchRepository guideElasticsearchRepository;

    @Override
    public List<GuideVO> selectListByDestinationName(String destinationName, Integer type) {
        List<GuideVO> guideVOS = guideRepository.selectListByDestinationName(destinationName, type);
        if (guideVOS.isEmpty()) {
            String message = "查询失败，请输入正确的关键词";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return guideVOS;
    }

    @Override
    public List<GuideVO> selectListByName(String destinationName, Integer num) {
        if (num != 1) {
            return guideRepository.trendingSelectListByName(destinationName);
        }
        return guideRepository.latestSelectListByName(destinationName);
    }

    @Override
    public List<GuideVO> selectList(String keywords) {
        Pageable pageable = PageRequest.of(0, 20);
        SearchPage<GuideVO> searchHits = guideElasticsearchRepository.customSearch(keywords, pageable);
        List<SearchHit<GuideVO>> content = searchHits.getContent();
        if (content.isEmpty()) {
            String message = "查询失败，请输入正确的关键词";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        return content.stream().map(SearchHit::getContent).collect(Collectors.toList());
    }

    @Override
    public void guideElasticsearch() {
        guideElasticsearchRepository.deleteAll();
        List<GuideVO> guideVOS = guideRepository.selectAll();
        guideElasticsearchRepository.saveAll(guideVOS);
    }
}
